import { Injectable } from '@nestjs/common';
import { decompressFromEncodedURIComponent } from 'lz-string';
import { ErrorPosition, handleErrorMessage, MessageInfo } from '@/util';
import { join, resolve } from 'path';
import * as moment from 'moment';
import { mkdirSync, appendFileSync, existsSync, writeFileSync, readdirSync } from 'fs';
@Injectable()
export class LogService {
  async create(data: string) {
    const log = JSON.parse(decompressFromEncodedURIComponent(data)) as {
      data: MessageInfo & {
        originPostion: ErrorPosition;
      };
    };
    if (log.data?.source) {
      log.data.originPostion = await handleErrorMessage(log.data);
    }
    const source = JSON.stringify(log) + '\n';
    const now = moment().format('YYYY-MM-DD');
    const dirPath = resolve(__dirname, '../../', 'web_logs');
    if (!existsSync(dirPath)) {
      mkdirSync(dirPath, { recursive: true });
    }
    const filePath = join(dirPath, `/${now}.log`);
    if (!existsSync(filePath)) {
      writeFileSync(filePath, source, 'utf-8');
    } else {
      appendFileSync(filePath, source);
    }
  }
}
